package net.wangds.utils;

import java.util.UUID;

/**
 * UUID工具.
 */
public final class UuidUtils {

    private static String TEMPLATE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghizklmnopqrstuvwxyz-_";

    /**
     * 随机生成一个UUID，并按照64进制转换为字符串.
     * @return 字符串.
     */
    public static String randomUuid2Radix64Str(){
        UUID uuid = UUID.randomUUID();
        return uuid2Radix64Str(uuid);
    }

    /**
     * 把一个UUID按照64进制转换为字符串.
     * @param uuid 目标UUID.
     * @return 字符串.
     */
    public static String uuid2Radix64Str(UUID uuid){
        StringBuffer buf = new StringBuffer();
        encodeLongAs64ToSb(uuid.getLeastSignificantBits(), buf);
        encodeLongAs64ToSb(uuid.getMostSignificantBits(), buf);
        return buf.toString();
    }

    private static void encodeLongAs64ToSb(long num, StringBuffer sb){
        for(int i=64;i>0;i-=6){
            int idx = (int)(num&Long.MAX_VALUE%64);
            sb.insert(0,TEMPLATE.charAt(idx));
            num>>=6;
        }
    }

}
